<template>
    <div class="person">
        姓: <input type="text" v-model="firstname"> <br>
        名: <input type="text" v-model="lastname"> <br>
        全名: <span> {{ fullname }} </span> <br>
        全名: <span> {{ fullname2 }} </span> <br>
        全名: <span> {{ fullname2 }} </span> <br>
        全名: <span> {{ fullname2 }} </span> <br>
        <button @click="changeFullname">修改全名</button>
    </div>
</template>

<script lang="ts">
export default {
    name: 'Person',
}
</script>

<script setup lang="ts">
import { ref, computed } from 'vue'
let firstname = ref('zhang')
let lastname = ref('三')
// 计算属性,有缓存
// 如此定义的计算属性是只读的,不可修改的(注意,firstname,lastname可以修改)
let fullname = computed(() => {
    let firstletter = firstname.value.slice(0, 1).toUpperCase()
    let lastletter = firstname.value.slice(1)
    // 页面展示多次,但只要依赖的值不变,就只会计算一次
    console.log("computed")
    return firstletter + lastletter + '-' + lastname.value
})

// 如此定义的计算属性,可读可写
let fullname2 = computed({
    get() {
        let firstletter = firstname.value.slice(0, 1).toUpperCase()
        let lastletter = firstname.value.slice(1)
        return firstletter + lastletter + '-' + lastname.value
    },
    set(newval) {
        console.log("set", newval)
        const [r0, r1] = newval.split("-")
        let firstletter = r0.slice(0, 1).toUpperCase()
        let lastletter = r0.slice(1)
        firstname.value = firstletter + lastletter
        lastname.value = r1
    }
})
const changeFullname = () => {
    console.log(fullname2.value)
    // 这里的fullname2.value,会触发set方法
    fullname2.value = 'li-si'
}
</script>

<style scoped>
.person {
    background-color: skyblue;
    box-shadow: 0 0 10px;
    border-radius: 10px;
    padding: 20px;
}

button {
    margin: 0 2px;
}

li {
    font-size: 15px;
}
</style>